<template>
  <n-card class="item-card" :bordered="true" size="small" @click="goToDetail" :class="`grade-bg-${item.grade}`">
    <!-- 物品图片 -->
    <div class="item-image" :class="`grade-bg-${item.grade}`">
      <img :src="item.pic" :alt="item.object_name" class="item-pic" />
      <div class="item-grade" :class="`grade-${item.grade}`">
        {{ formatGrade(item.grade) }}
      </div>
    </div>

    <!-- 物品信息 -->
    <div class="item-info">
      <n-ellipsis :line-clamp="2" class="item-name" @click.stop="searchByName(item.object_name)">
        {{ item.object_name }}
      </n-ellipsis>

      <!-- 物品详细信息区域 -->
      <div class="item-details">
        <!-- 类型信息 -->
        <div class="item-type-section">
          <div
            v-if="item.propDetails?.type"
            class="item-type-badge"
            :class="getTypeBadgeClass(item.propDetails.type)"
          >
            {{ item.propDetails.type }}
          </div>
          <div v-else class="item-type-badge item-type-unknown">
            未知类型
          </div>
        </div>

        <!-- 分类信息 -->
        <div class="item-category-section">
          <div v-if="item.category" class="category-info">
            <span class="category-primary">{{ getCategoryDisplayName(item.category.primary_class) }}</span>
            <span v-if="getCategoryDetailInfo().subTypeCn" class="category-separator">></span>
            <span v-if="getCategoryDetailInfo().subTypeCn" class="category-sub">{{ getCategoryDetailInfo().subTypeCn }}</span>
          </div>
        </div>

        <!-- 物品属性信息 -->
        <div class="item-properties">
          <div v-if="item.propDetails?.props_source" class="property-item">
            <span class="property-value">{{ item.propDetails.props_source }}</span>
          </div>
        </div>
      </div>

      <div class="item-price-section">
        <div class="item-card__current-price">
          <n-text class="item-card__price-label">当前价格</n-text>
          <n-text class="item-card__price-value">
            {{ formatHafCoin(item.price_change.price) }}
          </n-text>
        </div>

        <div class="item-card__price-comparison" v-if="item.price_24h_ago !== undefined">
          <div class="item-card__price-24h">
            <n-text class="item-card__price-24h-label">24h前</n-text>
            <n-text class="item-card__price-24h-value">
              {{ formatHafCoin(get24hAgoPrice()) }}
            </n-text>
            <n-text class="item-card__price-update-time">
              {{ getCurrentHourTime() }}
            </n-text>
          </div>
          <div class="price-change-display">
            <div class="price-change-info">
              <n-text class="item-card__price-change" :type="getPriceChangeType(item.price_24h_ago)">
                {{ formatPriceChange(item.price_24h_ago) }}
              </n-text>
              <n-text class="item-card__price-change-percent" :type="getPriceChangeType(item.price_24h_ago)">
                {{ formatPriceChangePercent(item.price_24h_ago) }}
              </n-text>
            </div>
          </div>
        </div>
      </div>
    </div>
  </n-card>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits } from 'vue'
import type { Item } from '@/types/items'
import { parseCategoryKey, getCategoryDisplayName } from '@/utils/categoryUtils'

// 引入样式
import '@/styles/components/itemlist/ItemCard.css'

const props = defineProps<{
  item: Item
}>()

const emit = defineEmits<{
  (e: 'search-name', name: string): void
  (e: 'show-detail', objectId: number): void
}>()

// 格式化哈夫币价格
const formatHafCoin = (price: number) => {
  return price ? `${price.toFixed(2)} 哈夫币` : '0.00 哈夫币'
}

// 计算24小时前价格
const get24hAgoPrice = () => {
  const currentPrice = props.item.price_change.price || 0
  const change = props.item.price_24h_ago || 0
  return currentPrice - change
}

// 格式化价格变化
const formatPriceChange = (change: number) => {
  if (!change) return '0.00'
  const sign = change > 0 ? '+' : ''
  return `${sign}${change.toFixed(2)}`
}

// 格式化价格变化百分比
const formatPriceChangePercent = (change: number) => {
  const previousPrice = get24hAgoPrice()

  if (!previousPrice || previousPrice === 0) return '0.00%'

  const percentChange = (change / previousPrice) * 100
  const sign = percentChange > 0 ? '+' : ''

  return `${sign}${percentChange.toFixed(2)}%`
}

// 获取当前整点时间
const getCurrentHourTime = () => {
  const now = new Date()
  const currentHour = now.getHours()
  const formattedHour = currentHour.toString().padStart(2, '0')

  return `更新时间：${formattedHour}:02 `
}

// 获取价格变化类型
const getPriceChangeType = (change: number) => {
  if (!change || change === 0) return 'default'
  return change > 0 ? 'error' : 'success'
}

// 格式化等级
const formatGrade = (grade: number) => {
  return `等级${grade}`
}

// 获取类型徽章样式类
const getTypeBadgeClass = (type: string) => {
  // 根据物品类型返回不同的样式类
  const typeMap: Record<string, string> = {
    '武器': 'type-weapon',
    '防具': 'type-armor',
    '配件': 'type-accessory',
    '弹药': 'type-ammo',
    '道具': 'type-item',
    '材料': 'type-material',
    '消耗品': 'type-consumable'
  }

  // 检查类型中是否包含关键词
  for (const [key, value] of Object.entries(typeMap)) {
    if (type.includes(key)) {
      return value
    }
  }

  return 'type-default'
}

// 获取分类详细信息
const getCategoryDetailInfo = () => {
  if (!props.item.category?.category_key) {
    return {
      secondClass: '',
      secondClassCn: '',
      subType: '',
      subTypeCn: ''
    }
  }

  return parseCategoryKey(props.item.category.category_key)
}

// 获取分类名称（保留向后兼容）
const getCategoryName = (categoryId: number) => {
  // 这里可以根据实际的分类数据进行映射
  const categoryMap: Record<number, string> = {
    1: '武器装备',
    2: '防护装备',
    3: '战术配件',
    4: '弹药物资',
    5: '消耗道具',
    6: '材料物品'
  }

  return categoryMap[categoryId] || '其他'
}

// 格式化更新时间
const formatUpdateTime = (updateTime: string) => {
  try {
    const date = new Date(updateTime)
    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
    const diffDays = Math.floor(diffHours / 24)

    if (diffDays > 0) {
      return `${diffDays}天前`
    } else if (diffHours > 0) {
      return `${diffHours}小时前`
    } else {
      return '刚刚'
    }
  } catch {
    return '未知'
  }
}

// 显示详情弹窗
const goToDetail = () => {
  emit('show-detail', props.item.object_id)
}

// 按名称搜索
const searchByName = (name: string) => {
  emit('search-name', name)
}
</script>

